package com.itbaizhan.banner.service.impl;

import com.itbaizhan.banner.mapper.BannerMapper;
import com.itbaizhan.banner.service.BannerService;
import com.itbaizhan.common.redis.dao.RedisDao;
import com.itbaizhan.common.vo.LivegoodsResult;
import com.itbaizhan.pojo.Banner;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 将该接口所有服务发布，可供远程调用
 */
@DubboService
public class BannerServiceImpl implements BannerService {

    private static final Logger log = LoggerFactory.getLogger(BannerServiceImpl.class);
    @Autowired
    private BannerMapper bannerMapper;
    @Value("${livegoods.nginx.host}")
    private String nginxHost;
    @Value("${livegoods.redis.banner}")
    private String bannerKey;
    //之前对spring data 的分装
    @Autowired
    private RedisDao redisDao;

    @Override
    public LivegoodsResult showBanner() {
        //先查缓存，有缓存直接返回缓存数据
        if(redisDao.hasKey(bannerKey)) {
            log.info("************* banner走缓存取数据 ***********");
            return redisDao.get(bannerKey);
        }
        List<Banner> bannerList = bannerMapper.selectBannerVisible();
        List<String> imgs = new ArrayList<String>();
        bannerList.forEach(banner->{
            imgs.add(nginxHost+banner.getUrl());
        });
        // 先添加缓存，时间为7天
        LivegoodsResult result = LivegoodsResult.ok(imgs);
        redisDao.set(bannerKey, result,7, TimeUnit.DAYS);
        log.info("************* banner走数据库取数据 ***********");
        return result;
    }
}
